//
//  RestaurantDetailViewController_iPad.m
//  RestaurantX
//
//  Created by Vinh Huynh on 6/26/12.
//  Copyright (c) 2012 _eBars GbR_. All rights reserved.
//

#import "RestaurantDetailViewController_iPad.h"
#import "MapView.h"
#import "UICRouteOverlayMapView.h"
#import "UICRouteAnnotation.h"
#import "RouteListViewController.h"
#import "MyLocationParser.h"

#define kCenterPointLatitude  49.000050
#define kCenterPointLongitude 12.121000
#define kSpanDeltaLatitude    5.263112
#define kSpanDeltaLongitude   5.697419

#define iphoneScaleFactorLatitude   9.0    
#define iphoneScaleFactorLongitude  11.0

@interface RestaurantDetailViewController_iPad () <MKMapViewDelegate, UICGDirectionsDelegate>{
    CLLocationDegrees zoomLevel;
	UILabel *restaurantName;
	UIImageView *restaurantImageView;
	UILabel *titleLabel;
	UITextView *timeTextView;
	CLLocation *currentLocation;
	RestaurantDetail *restaurantDetail;
	Restaurant *restaurant;
	IBOutlet UIView *titleBar;
	//
	MKMapView *routeMapView;
	UICRouteOverlayMapView *routeOverlayView;
	UICGDirections *diretions;
	NSString *startPoint;
	NSString *endPoint;
	NSArray *wayPoints;
	UICGTravelModes travelMode;
    UIInterfaceOrientation orientation;
}

@end

@implementation RestaurantDetailViewController_iPad

@synthesize titleLabel;
@synthesize restaurantName;
@synthesize restaurantImageView;
@synthesize timeTextView;
@synthesize restaurantDetail;
@synthesize restaurant;
@synthesize currentLocation;
//
@synthesize startPoint;
@synthesize endPoint;
@synthesize wayPoints;
@synthesize travelMode;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.titleView = titleBar;
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, WIDTH_IPAD, HEIGHT_IPAD)];
	[contentView setBackgroundColor:[UIColor whiteColor]];
	self.view = contentView;
	[contentView release];
    routeMapView = [[MKMapView alloc] init];
    [routeMapView setFrame:CGRectMake(0.0f, 150.0f, WIDTH_IPAD, 810.0f)];
	routeMapView.delegate = self;
	routeMapView.showsUserLocation = ShowsUserLocation;
	[contentView addSubview:routeMapView];
	
	[restaurantImageView removeFromSuperview];
	[contentView addSubview:restaurantImageView];
	[restaurantImageView setFrame:CGRectMake(10, 11, 236, 128)];
	
//	[contentView addSubview:titleBar];
//	[titleBar setFrame:CGRectMake(0, 0, WIDTH_IPAD, HEIGHT_TITLE_VIEW)];
	
	[contentView addSubview:timeTextView];
	[timeTextView setFrame:CGRectMake(300, 11, 430, 127)];
	
	[routeMapView release];
	
	routeOverlayView = [[UICRouteOverlayMapView alloc] initWithMapView:routeMapView];
	diretions = [UICGDirections sharedDirections];
	diretions.delegate = self;
	if (diretions.isInitialized) {
		[self update];
	}
}

- (void)viewDidUnload
{
    [self setTitleLabel:nil];
    [self setRestaurantImageView:nil];
    [self setTimeTextView:nil];
    [self setRestaurantName:nil];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    orientation = interfaceOrientation;
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown) {
        [routeMapView setFrame:CGRectMake(0.0f, 154.0f, WIDTH_IPAD, 810.0f)];
    }
    else {
        [routeMapView setFrame:CGRectMake(0.0f, 154.0f, HEIGHT_IPAD, WIDTH_IPAD - (restaurantImageView.frame.origin.y + restaurantImageView.frame.size.height + 10) )];
    }
	return YES;
}

- (IBAction)backButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
    [titleLabel release];
    [restaurantImageView release];
    [timeTextView release];
    [routeOverlayView release];
	[startPoint release];
	[endPoint release];
    [wayPoints release];
    [restaurantName release];
    [super dealloc];
}

- (void)update {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
	[routeMapView removeAnnotations:routeMapView.annotations];
	UICGDirectionsOptions *options = [[[UICGDirectionsOptions alloc] init] autorelease];
	options.travelMode = travelMode;
	if ([wayPoints count] > 0) {
		NSArray *routePoints = [NSArray arrayWithObject:startPoint];
		routePoints = [routePoints arrayByAddingObjectsFromArray:wayPoints];
		routePoints = [routePoints arrayByAddingObject:endPoint];
		[diretions loadFromWaypoints:routePoints options:options];
	} else {
		[diretions loadWithStartPoint:startPoint endPoint:endPoint options:options];
	}    
}

- (void)moveToCurrentLocation:(id)sender {
	[routeMapView setCenterCoordinate:[routeMapView.userLocation coordinate] animated:YES];
}

- (void)addPinAnnotation:(id)sender {
	UICRouteAnnotation *pinAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[routeMapView centerCoordinate]
																				  title:nil
																		 annotationType:UICRouteAnnotationTypeWayPoint] autorelease];
	[routeMapView addAnnotation:pinAnnotation];
}

- (void)showRouteListView:(id)sender {
	RouteListViewController *controller = [[RouteListViewController alloc] initWithStyle:UITableViewStyleGrouped];
	controller.routes = diretions.routes;
	UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
	[self presentModalViewController:navigationController animated:YES];
	[controller release];
	[navigationController release];
}

#pragma mark <UICGDirectionsDelegate> Methods

- (void)directionsDidFinishInitialize:(UICGDirections *)directions {
	[self update];
}

- (void)directions:(UICGDirections *)directions didFailInitializeWithError:(NSError *)error {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:[error localizedFailureReason] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	[alertView show];
	[alertView release];
}

- (void)directionsDidUpdateDirections:(UICGDirections *)directions {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	
	// Overlay polylines
	UICGPolyline *polyline = [directions polyline];
	NSArray *routePoints = [polyline routePoints];
	[routeOverlayView setRoutes:routePoints];
	
	// Add annotations
	UICRouteAnnotation *startAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints objectAtIndex:0] coordinate]
																					title:startPoint
																		   annotationType:UICRouteAnnotationTypeStart] autorelease];
	UICRouteAnnotation *endAnnotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[[routePoints lastObject] coordinate]
																				  title:endPoint
																		 annotationType:UICRouteAnnotationTypeEnd] autorelease];
	if ([wayPoints count] > 0) {
		NSInteger numberOfRoutes = [directions numberOfRoutes];
		for (NSInteger index = 0; index < numberOfRoutes; index++) {
			UICGRoute *route = [directions routeAtIndex:index];
			CLLocation *location = [route endLocation];
			UICRouteAnnotation *annotation = [[[UICRouteAnnotation alloc] initWithCoordinate:[location coordinate]
																					   title:[[route endGeocode] objectForKey:@"address"]
																			  annotationType:UICRouteAnnotationTypeWayPoint] autorelease];
			[routeMapView addAnnotation:annotation];
		}
	}
	
	[routeMapView addAnnotations:[NSArray arrayWithObjects:startAnnotation, endAnnotation, nil]];
}

- (void)directions:(UICGDirections *)directions didFailWithMessage:(NSString *)message {
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Map Directions" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
	[alertView show];
	[alertView release];
}

#pragma mark <MKMapViewDelegate> Methods

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = YES;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
	routeOverlayView.hidden = NO;
	[routeOverlayView setNeedsDisplay];
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
	static NSString *identifier = @"RoutePinAnnotation";
	
	if ([annotation isKindOfClass:[UICRouteAnnotation class]]) {
		MKPinAnnotationView *pinAnnotation = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
		if(!pinAnnotation) {
			pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier] autorelease];
		}		
		if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeStart) {
			pinAnnotation.image=[UIImage imageNamed:@"icon_greenA.png"];
		} else if ([(UICRouteAnnotation *)annotation annotationType] == UICRouteAnnotationTypeEnd) {
			pinAnnotation.image=[UIImage imageNamed:@"icon_greenB.png"];
		} 
		
		pinAnnotation.animatesDrop = YES;
		pinAnnotation.enabled = YES;
		pinAnnotation.canShowCallout = YES;
		return pinAnnotation;
	} else {
		return [routeMapView viewForAnnotation:routeMapView.userLocation];
	}
}
@end
